package com.github.ylt.protocol.request;

import com.sun.net.httpserver.HttpServer;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.nio.channels.SocketChannel;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;

public class Request extends HttpRequest {
    private final Map<String, Object> headers;
    private SocketChannel socketChannel;
    private Map<String,String> parameters;

    public Request(Map<String, Object> headers,SocketChannel socketChannel,Map<String,String> parameters) {
        this.headers = headers;
        this.socketChannel = socketChannel;
        this.parameters = parameters;
    }


    public void setSocketChannel(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public Optional<BodyPublisher> bodyPublisher() {
        return Optional.empty();
    }

    @Override
    public String method() {
        return headers.get("METHOD").toString();
    }

    @Override
    public Optional<Duration> timeout() {
        return Optional.empty();
    }

    @Override
    public boolean expectContinue() {
        return false;
    }

    @Override
    public URI uri() {
        try {
            return new URI("http://"+headers.get("HOST")+headers.get("PATH"));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Optional<HttpClient.Version> version() {
        return Optional.of(HttpClient.Version.HTTP_1_1);
    }

    @Override
    public HttpHeaders headers() {
        Builder builder = HttpRequest.newBuilder();
        headers.forEach((key,value)->{
            if(!"CONNECTION".equals(key) && !"HOST".equals(key) && !"PATH".equals(key)){
                builder.header(key,value.toString());
            }

        });
        try {
            builder.uri(new URI("http://"+headers.get("HOST").toString()+headers.get("PATH").toString()));
            return builder.build().headers();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    public Map<String, Object> getHeaders() {
        return headers;
    }

    public String getPath(){
        return headers.get("PATH").toString();
    }
    
    public SocketChannel getStream(){
        return socketChannel;
    }

    public Map<String,String> getParameters(){
        return parameters;
    }

    public void setParameters(Map<String, String> parameters) {
        this.parameters = parameters;
    }
}
